package mapreduce.sortable;

import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * 一般用来排序的字段都要放在K中。如果有多个，就创建类封装。
 * 另外要求可序列化。Writable接口即可序列化。WritableComparable是可排序可序列化
 */
public class MyComprable implements WritableComparable<MyComprable> {
    //字母
    private String letter;
    //数字
    private int number;

    public MyComprable() {}
    public MyComprable(String letter, int number) {
        this.set(letter, number);
    }

    /*
    比较器
     */
    public int compareTo(MyComprable o) {
        //每次比较都是调用该方法的对象与传递的参数进行比较
        int comp = this.letter.compareTo(o.getLetter());
        if (comp == 0){    //等于0说明字母相等，再比较数字
            comp = Integer.valueOf(this.number).compareTo(
                    Integer.valueOf(o.getNumber()));
        }
        return comp;
    }

    /**
     * 序列化
     */
    public void write(DataOutput dataOutput) throws IOException {
        dataOutput.writeUTF(letter);
        dataOutput.writeInt(number);
    }
    /**
     * 反序列化
     */
    public void readFields(DataInput dataInput) throws IOException {
        this.letter = dataInput.readUTF();
        this.number = dataInput.readInt();
    }

    /**
     * 方便设置字段
     */
    public void set(String letter, int number) {
        this.letter = letter;
        this.number = number;
    }
    public String getLetter() {
        return letter;
    }

    public void setLetter(String letter) {
        this.letter = letter;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    @Override
    public String toString() {
        return "MyComprable{" +
                "letter='" + letter + '\'' +
                ", number=" + number +
                '}';
    }
}
